package util;

import org.sqlite.SQLiteConfig;
import org.sqlite.SQLiteDataSource;
import org.sqlite.SQLiteOpenMode;
import task.DBInit;

import javax.sql.DataSource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @Author: yuisama
 * @Date: 2022/6/10 15:55
 * @Description:SQLite DB utils
 */
public class DBUtil {
    private static volatile DataSource DATA_SOURCE;
    private static volatile Connection connection;

    /**
     * 获取数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        synchronized (DBUtil.class) {
            if (connection == null) {
                System.out.println(Thread.currentThread().getName() + "获取数据库连接");
                connection = getDataSource().getConnection();
            }
        }
        return connection;
    }

    /**
     * Double-Check SingleTon
     * @return
     */
    private static DataSource getDataSource() {
        if (DATA_SOURCE == null) {
            synchronized (DBUtil.class) {
                if (DATA_SOURCE == null) {
                    SQLiteConfig config = new SQLiteConfig();
                    // 设置日期格式
                    config.setDateStringFormat(Util.DATA_PATTEN);
//                    config.setBusyTimeout(1000);
                    DATA_SOURCE = new SQLiteDataSource(config);
                    ((SQLiteDataSource) DATA_SOURCE).setUrl(getUrl());
                }
            }
        }
        return DATA_SOURCE;
    }

    private static String getUrl() {
        // 获取编译文件夹路径
        // 默认为target/classes/
//        URL classesPathURL = DBInit.class.getClassLoader().getResource("./");
//        System.out.println("classesPathURL为 : " + classesPathURL);
        // 获取classes的父路径，即target根目录
        // 如果直接执行main方法则会得到当前class的绝对路径。
        // 如果封装在jar包里面执行jar包那么会得到当前jar包的绝对路径
        String classesPath = DBUtil.class.getProtectionDomain()
                .getCodeSource().getLocation().getFile();
        File classesDir = null;
        try {
            classesDir  = new File(URLDecoder.decode(classesPath, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
//        System.out.println("classesPath : " + classesPath);
        String dir = classesDir.getParent();
//        System.out.println("dir : " + dir);
        // 在target根目录下创建数据库
        String url = "jdbc:sqlite://" + dir + File.separator + "search_everywhere.db";
        System.out.println("获取数据库连接Url为:" + url);
        return url;
    }

    public static void close(Statement statement) {
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void close(ResultSet rs,Statement statement) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        close(statement);
    }

    public static void main(String[] args) {
        getUrl();
    }
}
